package gwtadmin.client;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class FormWsdlList extends VerticalPanel implements BlurHandler,FocusHandler,KeyPressHandler,KeyUpHandler,AsyncCallback<String> {

	private TextBox filter;
	private TableOfServices tos;
	private IWsdlManager wsdlMan;
	
	private boolean filterWorks = false;
	
	public FormWsdlList(IWsdlManager wsdlManager) {
		
		wsdlMan = wsdlManager;
		tos = new TableOfServices(wsdlManager);
		filter = new TextBox();
		
		filter.setWidth("100%");
		filter.setText("Filter");
		filter.setStylePrimaryName("filter");
		filter.addBlurHandler(this);
		filter.addFocusHandler(this);
		filter.addKeyPressHandler(this);
		filter.addKeyUpHandler(this);
		
		addStyleName("undecorFrame");

		add(filter);
		add(tos);
	}
	
	public void setServices(String[] svcs) {
		
		if (svcs == null)
			return;

		tos.removeServices();
		for (String svc : svcs)
			tos.addService(svc);
	}
	
	public void removeServices() {
		tos.removeServices();
	}
	
	public void showWait(boolean show) {
		tos.showWait(show);
	}

	@Override
	public void onBlur(BlurEvent event) {
		if (filterWorks && filter.getText().equals("")) {
			filter.setStylePrimaryName("filter");
			filter.setText("Filter");
			filterWorks = false;
		}
	}

	@Override
	public void onFocus(FocusEvent event) {
		if (!filterWorks) {
			filter.setText("");
			filter.setStylePrimaryName("filter-act");
			filterWorks = true;
		}
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if (event.getCharCode() == (char)13)
			tos.setFilter(filter.getText());
	}

	@Override
	public void onKeyUp(KeyUpEvent event) {
		tos.setFilter(filter.getText());
	}
	
	@Override
	public void onSuccess(String messageXml) {
		if (!messageXml.equals("")) {
			String[] wsdlList = wsdlMan.parseWsdlList(messageXml);
			setServices(wsdlList);
		}
	}

	@Override
	public void onFailure(Throwable caught) {
		Window.alert("Error failure");
	}
}
